package com.kdl.webconfig.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kdl.webconfig.exception.AuthException;
import com.kdl.webconfig.service.IUserService;
import com.kdl.webconfig.utils.JWTUtils;
import com.kdl.webconfig.entity.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        if (StringUtils.isBlank(token)) {
            throw new AuthException("无token，请重新登录");
        }
        // 获取 token中的userId,根据userId查询数据库，检查用户是否存在
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new AuthException("token解析异常");
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new AuthException("用户不存在，请重新登录");
        }

        // 验证 token
        try {
            JWTUtils.verify(token);
        } catch (JWTVerificationException e) {
            throw new AuthException("token失效,请重新登录");
        }

        return true;
    }
}

